<?php


namespace sources\service\DataBase;


use sources\service\Dir;
use think\facade\Db;
use think\facade\Config;

class Import
{
    
    protected $error;
    
    // 数据库操作
    public function __construct()
    {
    }
    
    // 返回错误信息
    public function getError()
    {
        return $this->error;
    }
    
    
    // 获取文件
    public function getFile($db_name, $is_all = false)
    {
        // 备份文件路径
        $ds    = DIRECTORY_SEPARATOR;
        $path  = app()->getRootPath() . 'bak' . $ds . '_sql' . $ds;
        $start = strlen($db_name . '-');
        
        //  获取最新的文件
        $result = '';
        $max    = 0;
        $news   = [];
        $dir    = new Dir();
        $files  = $dir->read($path);
        foreach($files as $file) {
            $base  = basename($file);
            $date  = substr($base, $start, -4);
            $date  = str_replace('：', ':', $date);
            $stamp = strtotime($date);
            
            // 重新定义
            $news[$stamp] = $file;
            if ($max < $stamp) {
                $max = $stamp;
            }
        }
        if ($is_all) {
            return $news;
        }
        
        if ($max > 0) {
            $result = $news[$max];
        }
        return $result;
    }
    
    // 删除数据表
    public function drop($db_name, $connect = '')
    {
        $connect = $connect ? $connect : Config::get('database.default');
        $tables  = DB::connect($connect)->query("SHOW TABLES;");
        foreach($tables as $table) {
            $tableName = $table['Tables_in_' . $db_name];
            // 删除本地数据表
            echo ' == 删除本地数据表：' . $tableName . chr(10);
            DB::connect($connect)->query("DROP TABLE " . $tableName);
        }
    }
    
    // 执行备份操作
    public function import($file, $connect = '')
    {
        $cline   = chr(10);
        $content = file_get_contents($file);
        
        // 直接分解
        // $_array = explode(';', $content); // 因为数据表中也可能有分号，直接用分号分割导入的时候可能报错
        
        // 替换分解
        $connect = $connect ? $connect : Config::get('database.default');
        $content = str_replace("\r", "\n", $content);
        $_array  = explode(";\n", trim($content));
        $failSql = [];
        $index   = 0;
        unset($content);
        
        foreach($_array as $_row) {
            // 组合sql
            $_sql    = '';
            $queries = explode("\n", trim($_row));
            $queries = array_filter($queries);
            foreach($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-') {
                    $_sql .= $query;
                }
            }
            
            // 判断
            if (empty($_sql)) {
                continue;
            }
            
            // 如果是添加 才数据消息
            if (strpos($_sql, 'CREATE TABLE ') === 0) {
                $index   = 0;
                echo ' == 创建数据表：' . $_sql . $cline;
                echo ' == 导入数据... ...' . $cline;
            }
            
            // 执行sql语句
            $result = Db::connect($connect)->execute($_sql);
            if ($result === false) {
                $failSql[] = $_sql;
                echo ' == 导入失败...' . $cline;
                echo ' ' . $_sql . $cline . $cline;
            }else{
                $index++;
                echo ' == 成功导入第'.$index.'条数据...' . $cline;
            }
        }
        
        // 保存错误语句
        if (!empty($failSql)) {
            $ds       = DIRECTORY_SEPARATOR;
            $path     = app()->getRootPath() . 'bak' . $ds;
            $filename = $path . date("Y-m-d H：i：s") . ".sql";
            file_put_contents($filename, $failSql);
        }
    }
    
    
    // 暂无使用
    function split_sql($sql)
    {
        $sql = trim($sql);
        $sql = preg_replace("\n#[^\n]*\n", "\$1", $sql);
        //$sql = ereg_replace("\n#[^\n]*\n", "\n", $sql);
        
        $buffer    = array();
        $ret       = array();
        $in_string = false;
        
        for($i = 0; $i < strlen($sql) - 1; $i++) {
            if ($sql[$i] == ";" && !$in_string) {
                $ret[] = substr($sql, 0, $i);
                $sql   = substr($sql, $i + 1);
                $i     = 0;
            }
            
            if ($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") {
                $in_string = false;
            } elseif (!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
                $in_string = $sql[$i];
            }
            if (isset($buffer[1])) {
                $buffer[0] = $buffer[1];
            }
            $buffer[1] = $sql[$i];
        }
        
        if (!empty($sql)) {
            $ret[] = $sql;
        }
        return ($ret);
    }
    
    // 正常使用的
    function sql_split($sql, $charset = 'UTF8')
    {
        $sql   = str_replace("\r", "\n", $sql);
        $ret   = array();
        $num   = 0;
        $array = explode(";\n", trim($sql));
        unset($sql);
        foreach($array as $item) {
            $ret[$num] = '';
            $queries   = explode("\n", trim($item));
            $queries   = array_filter($queries);
            foreach($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
            }
            $num++;
        }
        
        return ($ret);
    }
}
